package cn.weixin.interceptor;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.weixin.common.config.AppConfig;

public class CheckInterceptor extends HandlerInterceptorAdapter {
	private static Logger logger = LoggerFactory.getLogger(CheckInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		Map temp = request.getParameterMap();
		for (Iterator<Map.Entry> it = temp.entrySet().iterator(); it.hasNext();) {
			Entry e = it.next();
			logger.info(e.getKey().toString());
		}

		try {
			List<String> list = new ArrayList<String>();
			list.add(timestamp);
			list.add(nonce);
			list.add(AppConfig.TOKEN);
			// 排序
			Collections.sort(list);

			StringBuffer sb = new StringBuffer("");
			for (String str : list) {
				sb.append(str);
			}
			String sec = DigestUtils.sha1Hex(sb.toString());
			if (sec.equals(signature)) {
				return true;
			}
			return false;
		} catch (Exception e) {
			return false;
		}
	}

}
